package com.project.frba.bifront.client.view.dashboard;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.event.PanelListenerAdapter;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.layout.FitLayout;
import com.project.frba.bifront.client.BiPanel;
import com.project.frba.bifront.client.model.Dashboard;
import com.project.frba.bifront.client.rpc.DashboardServices;
import com.project.frba.bifront.client.rpc.DashboardServicesAsync;
import com.project.frba.bifront.client.view.MessageWindow;
import com.project.frba.bifront.client.view.users.ListGridListener;

public class DashboardList extends Composite {
	
	private Window mainWindow = new Window();
	
	private BiPanel biPanel;
	
	private GridPanel gridPanel = new GridPanel();
	
	private Button btAdd = new Button("Agregar Tablero");
	
	private Button btRemove = new Button("Eliminar");
	
	private Long selectedDashboard = null;
	
	private Integer selectedType = null;
	
	private RecordDef recordDef = null;
	
	public DashboardList(BiPanel panel) {
		this.biPanel = panel;
		loadActions();
		
		FieldDef[] fieldDef = new FieldDef[] { 
				new StringFieldDef("id"),
				new StringFieldDef("name"),
				new IntegerFieldDef("type") 
				};
		recordDef = new RecordDef(fieldDef);

		ColumnConfig[] columns = new ColumnConfig[] {
				new ColumnConfig("ID", "id", 40, false, null),
				new ColumnConfig("Nombre", "name", 160, true, null),
				new ColumnConfig("Cantidad de graficos", "type", 200 , false, null)
			};
		
		ColumnModel columnModel = new ColumnModel(columns);
		
		Store store = new Store(recordDef);
		
		gridPanel.setStore(store);
		gridPanel.setColumnModel(columnModel);
		gridPanel.setFrame(false);  
		gridPanel.setStripeRows(true);  
		gridPanel.setHeight(250);  
		gridPanel.setWidth(325);
		
		getDashboards();
		
		mainWindow.setTitle("Descriptores");
		mainWindow.setLayout(new FitLayout());
		mainWindow.setResizable(false);
		mainWindow.add(gridPanel);
		mainWindow.setWidth(400);
		mainWindow.setButtons(new Button[]{btAdd, btRemove});
		
		mainWindow.addListener(new PanelListenerAdapter(){
			public void onClose(Panel panel) {
				biPanel.refreshDashboards(); 
			}
		});
		
		initWidget(mainWindow);
		mainWindow.show();
	}

	private void getDashboards() {
		AsyncCallback<List<Dashboard>> callback = new AsyncCallback<List<Dashboard>>(){
			public void onFailure(Throwable caught) {
				new MessageWindow("No se pudieron obtener los usuarios");
			}
			
			public void onSuccess(List<Dashboard> dashboards) {
				loadListing(dashboards);
			}
		};
		
		DashboardServicesAsync dashboardServices = (DashboardServicesAsync)GWT.create(DashboardServices.class);
		dashboardServices.getMyDashboards(callback);
	}
	
	public void reload() {
		getDashboards();
	}
	
	private void loadListing(List<Dashboard> dashboards) {
		Store store = gridPanel.getStore();
		store.removeAll();
		
		for (Dashboard dashboard : dashboards) {
			store.add(recordDef.createRecord(dashboard.getKey(), new Object[] {
					dashboard.getId().toString(),
					dashboard.getName(),
					dashboard.getType().toString()
					}));
			store.commitChanges();
		}
	}

	private void loadActions() {
		final DashboardList me = this;
		btAdd.addListener(new ButtonListenerAdapter(){
			public void onClick(Button button, EventObject e) {
				new DashboardForm(0L, Dashboard.DUAL,  me);
			}
		});
		
		btRemove.addListener(new ButtonListenerAdapter(){
			public void onClick(Button button, EventObject e) {
				if(selectedDashboard != null){
					removeDashboard(selectedDashboard);
				}
			}
		});
		
		gridPanel.addGridListener(new ListGridListener(){
			public void onDblClick(EventObject e) {
				Record record = gridPanel.getSelectionModel().getSelected();
				selectedDashboard = new Long(record.getAsString("id"));
				selectedType = record.getAsInteger("type");
				new DashboardForm(selectedDashboard, selectedType,  me);
			}
			
			public void onClick(EventObject e) {
				Record record = gridPanel.getSelectionModel().getSelected();
				selectedDashboard = new Long(record.getAsString("id"));
				selectedType = record.getAsInteger("type");
			}
		});
	}
	
	private void removeDashboard(Long selectedDashboard) {
		AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>(){
			public void onFailure(Throwable caught) {
				new MessageWindow("Error en el servicio.");
			}
			
			public void onSuccess(Boolean result) {
				if (result) {
					//Esto es asincronico si demorase mucho y tuviera seleccionado otro antes de que actualiza borra uno q no corresponde.
					Record record = gridPanel.getSelectionModel().getSelected();
					Store store = gridPanel.getStore();
					store.remove(record);
					store.commitChanges();
				} else {
					new MessageWindow("Ha ocurrido un error al intentar eliminar el tablero.");
				}
			}
		};
		
		DashboardServicesAsync dashboardServices = (DashboardServicesAsync)GWT.create(DashboardServices.class);
		dashboardServices.removeDashboard(selectedDashboard, selectedType, callback);
	}

}
